Telegram Group & Telegram Channel
🐍 Задача по Python: Ловушка замыканий

Что выведет следующий код?


def create_funcs():
funcs = []
for i in range(3):
def f():
return i
funcs.append(f)
return funcs

for func in create_funcs():
print(func())


Варианты ответа:
A)

1
2


B)

2
2


C)

0
0


D) Ошибка выполнения


---

Правильный ответ: B

Почему:
Это классическая late binding: функция
f() не сохраняет значение i на момент создания, а берёт его из текущей области видимости при вызове.
К моменту вызова
i == 2 (последнее значение в range(3)), поэтому все три функции возвращают 2.

Чтобы избежать этого — можно использовать аргументы по умолчанию:
def f(i=i): return i



tg-me.com/pro_python_code/1781
Create:
Last Update:

🐍 Задача по Python: Ловушка замыканий

Что выведет следующий код?


def create_funcs():
funcs = []
for i in range(3):
def f():
return i
funcs.append(f)
return funcs

for func in create_funcs():
print(func())


Варианты ответа:
A)

1
2


B)

2
2


C)

0
0


D) Ошибка выполнения


---

Правильный ответ: B

Почему:
Это классическая late binding: функция
f() не сохраняет значение i на момент создания, а берёт его из текущей области видимости при вызове.
К моменту вызова
i == 2 (последнее значение в range(3)), поэтому все три функции возвращают 2.

Чтобы избежать этого — можно использовать аргументы по умолчанию:
def f(i=i): return i

BY Python RU


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/pro_python_code/1781

View MORE
Open in Telegram


Python RU Telegram | DID YOU KNOW?

Date: |

Telegram hopes to raise $1bn with a convertible bond private placement

The super secure UAE-based Telegram messenger service, developed by Russian-born software icon Pavel Durov, is looking to raise $1bn through a bond placement to a limited number of investors from Russia, Europe, Asia and the Middle East, the Kommersant daily reported citing unnamed sources on February 18, 2021.The issue reportedly comprises exchange bonds that could be converted into equity in the messaging service that is currently 100% owned by Durov and his brother Nikolai.Kommersant reports that the price of the conversion would be at a 10% discount to a potential IPO should it happen within five years.The minimum bond placement is said to be set at $50mn, but could be lowered to $10mn. Five-year bonds could carry an annual coupon of 7-8%.

What is Telegram Possible Future Strategies?

Cryptoassets enthusiasts use this application for their trade activities, and they may make donations for this cause.If somehow Telegram do run out of money to sustain themselves they will probably introduce some features that will not hinder the rudimentary principle of Telegram but provide users with enhanced and enriched experience. This could be similar to features where characters can be customized in a game which directly do not affect the in-game strategies but add to the experience.

Python RU from cn


Telegram Python RU
FROM USA